# -*- coding: utf-8 -*-

from email.mime.text import MIMEText
import urllib2
import httplib
import time
import re
import sys
import smtplib
from email.header import Header
from email.utils import parseaddr, formataddr

reload(sys)
sys.setdefaultencoding('utf8')
weather_url = 'http://www.weather.com.cn/weather/101020100.shtml'

def replace_html(s):
    return s.replace('<span>','').replace('</span>','').replace('<i>','').replace('</i>','').replace('\n','')

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr(( \
        Header(name, 'utf-8').encode(), \
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))

def case_weather(list):

    if True in map(lambda x:"今天" in x,list ) and True in map(lambda x:"雨" in x,list):
        return '今天有雨不要忘记拿伞'+'今天的天气是：'+replace_html(list[1])
    if True in map(lambda x:"明天" in x,list ) and True in map(lambda x:"雨" in x,list):
        return '明天有雨不要忘记拿伞' + '明天'+replace_html(list[0])+'的天气是：' + replace_html(list[1])
    else:
        return replace_html(list[0])+'的天气你也看看吧,'+replace_html(list[1])+',温度：'+replace_html(list[2])

def get_weather(url):
    user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36'
    headers = {'User-Agent': user_agent, 'timeout': 60}
    request = urllib2.Request(url, headers=headers)
    try:
        response = urllib2.urlopen(request)
    except (IOError, httplib.HTTPException, httplib.BadStatusLine) as e:
        print url + '列表页面发生异常', e
        time.sleep(60)
        return get_weather(url)
    else:

        conent = response.read()
        pattern = re.compile('<li class="sky skyid.*?">.*?<h1>(.*?)</h1>.*?<p title=".*?" class="wea">(.*?)</p>.*?<p class="tem">'\
                             +'(.*?)</p>',re.S)
        items = re.findall(pattern,conent)
        return items

msg = MIMEText('\n'.join(map(case_weather,get_weather(weather_url))), 'plain', 'utf-8')

# 输入Email地址和口令:
from_addr = 'your mail address'
password = 'your SSL  password'

# 输入SMTP服务器地址:
smtp_server = 'smtp.qq.com'
# 输入收件人地址:
to_addr = '903784816@qq.com'
msg['From'] = _format_addr(u'来自自己的问候 <%s>' % from_addr)
msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
msg['Subject'] = Header(u'注意天气，少吃多做', 'utf-8').encode()

server = smtplib.SMTP_SSL(smtp_server, 465) # 465
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

